

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.muse.core.AbstractEnvironment;
import org.apache.muse.util.xml.XmlUtils;
import org.apache.muse.ws.addressing.EndpointReference;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Element;
import org.xmlpull.v1.builder.XmlBuilderException;
import org.xmlpull.v1.builder.XmlElement;

import xsul.XmlConstants;
import xsul.soap.SoapUtil;

public class MyEnviorment extends AbstractEnvironment {

	@Override
	public InputStream getDataResourceStream(String path) {
		String mypath = path;
		if(mypath.startsWith("/")){
			mypath = mypath.substring(1);
		}
		InputStream instrem = Thread.currentThread().getContextClassLoader().getResourceAsStream(mypath);
		if(instrem == null){
			return super.getDataResourceStream(path);
		}else{
			return instrem;
		}
		
	}

	public EndpointReference getDeploymentEPR() {
		try {
			return new EndpointReference(new URI("http://127.0.0.1:5555/?wsdl"));
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public File getRealDirectory() {
		// TODO Auto-generated method stub
		return new File(".");
	}
	
	
	public Element convertToDOM(XmlElement envelope,SoapUtil soaputils)throws WSDMException{
		try {
			String inputMessage = XmlConstants.BUILDER.serializeToString(envelope);
			return XmlUtils.createDocument(new ByteArrayInputStream(inputMessage.getBytes())).getDocumentElement();
		} catch (Exception e) {
			throw new WSDMException(e);
		}
 	}
	
	
	public XmlElement convertToXsulXml(Element bodyContnet)throws WSDMException{
		try {
//			StringWriter writer = new StringWriter();
//			OutputFormat format = new OutputFormat(bodyContnet.getOwnerDocument());
//			  XMLSerializer output = new XMLSerializer(writer, format);
//			  output.serialize(bodyContnet);
//String responseMessage = writer.getBuffer().toString();			
			String responseMessage = XmlUtils.toString(bodyContnet, false);
			  
//			  System.out.println(responseMessage);
			  return XmlConstants.BUILDER.parseFragmentFromReader(new StringReader(responseMessage));
		} catch (Exception e) {
			throw new WSDMException(e);
		}
	}

	@Override
	public String getDefaultURI() {
		// TODO Auto-generated method stub
		return "";
	}

}
